package Server.controller;

import Plug.result.RetResponse;
import Plug.result.RetResult;
import Server.dao.MessageDao;
import Server.dao.UsersDao;
import Server.entity.Message;
import Server.entity.Users;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("MessageController")
public class MessageController {
    @Autowired
    private MessageDao messageDao;
    @Autowired
    private UsersDao usersDao;

    @RequestMapping("GetMyMessage")
    public RetResult GetMyMessage(){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        List<Message> ls = messageDao.findByUserAndReadMIOrderByModifiedTime(fspuser,0);
        JSONArray jsonArray = new JSONArray();
        for(Message ms:ls){
            if(ms.getShopSpec()!=null){
                ms.setReadMI(1);
                messageDao.saveAndFlush(ms);
            }
            JSONObject jo = new JSONObject();
            jo.put("username","财旺管家");
            jo.put("avatar","./depot/admin.png");
            jo.put("id","1111111");
            jo.put("type","friend");
            jo.put("content",ms.getMessage());
            jsonArray.add(jo);
            /*ms.setReadMI(1);
            messageDao.saveAndFlush(ms);*/
        }
        return RetResponse.makeOKRsp(jsonArray);
    }

    @RequestMapping("SetMessage")
    public RetResult GetMyMessage(@RequestBody Message message){
        Users fspuser = (Users) SecurityUtils.getSubject().getSession().getAttribute("Users");
        message.setAuthor(fspuser);
        message.setReadMI(0);
        message.setUser(usersDao.findByUuid(message.getUser().getUuid()));
        messageDao.save(message);
        return RetResponse.makeOKRsp();
    }
}
